package com.kun.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kun.entity.Role;
import com.kun.entity.User;
import com.kun.service.role.RoleServiceImpl;
import com.kun.service.user.UserService;
import com.kun.service.user.UserServiceImpl;
import com.kun.util.Constants;
import com.kun.util.MyUtils;
import com.kun.util.PageSupport;
import com.mysql.jdbc.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import static com.kun.util.Constants.USER_SESSION;

//实现Servlet复用
public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");

        if(method != null){
            switch (method) {
                case "savepwd":
                    updatePwd(req, resp);
                    break;
                case "pwdmodify":
                    pwdModify(req, resp);
                    break;
                case "query":
                    query(req, resp);
                    break;
                case "add":
                    add(req, resp);
                case "getrolelist":
                    getRoleList(req,resp);
                    break;
                case "ucexist":
                    isExist(req,resp);
                    break;
                case "deluser":
                    delUserById(req,resp);
                    break;
                case "modify"://跳转到用户修改页面
                    toUserPageById(req,resp,"usermodify.jsp");
                    break;
                case "view"://跳转到用户查看页面
                    toUserPageById(req,resp,"userview.jsp");
                    break;
                case "modifyexe"://修改用户信息
                    modify(req,resp);
                    break;
            }
        }

    }

    private void modify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端参数
        String uid = req.getParameter("uid");
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");
        //封装为User对象
        User user = new User();
        user.setId(Long.valueOf(uid));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        //获取当前管理员参数
        User u = (User) req.getSession().getAttribute(USER_SESSION);
        user.setModifyBy(Math.toIntExact(u.getId()));
        user.setModifyDate(new Date());
        //调用Service
        new UserServiceImpl().modifyUser(user);
        toUserPageById(req,resp,"usermodify.jsp");
    }


    //根据id获取用户信息并将信息发送到 用户修改页面
    private void toUserPageById(HttpServletRequest req, HttpServletResponse resp,String url) throws ServletException, IOException {
        String uid = req.getParameter("uid");
        if(!StringUtils.isNullOrEmpty(uid)){
            Long id = Long.parseLong(uid);
            User user = new UserServiceImpl().getUserByID(id);
            req.setAttribute("user",user);
            req.getRequestDispatcher(url).forward(req,resp);
        }
    }

    //通过ID删除用户
    private void delUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String uid = req.getParameter("uid");
        String result = null;
        UserServiceImpl userService = new UserServiceImpl();
        long id = Long.parseLong(uid);
        resp.setContentType("application/json");//设置返回JSON值
        PrintWriter writer = resp.getWriter();
        JSONObject js = new JSONObject();
        if(userService.getUserByID(id) == null){//不存在
            result = "notexist";
        }else if(userService.delUser(id)){
            result = "true";
        }else {
            result = "false";
        }
        js.put("delResult",result);
        writer.write(js.toJSONString());
        writer.close();
    }

    //判断指定userCode用户是否存在
    private void isExist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userCode = req.getParameter("userCode");
        User user = new UserServiceImpl().getUserByUserCode(userCode);
        resp.setContentType("application/json");//设置返回JSON值
        JSONObject json = new JSONObject();
        if(user != null){
            json.put("userCode","exist");
        }else {
            json.put("userCode","notExist");
        }
        PrintWriter writer = resp.getWriter();
        writer.write(json.toJSONString());
        writer.close();
    }

    public void getRoleList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ArrayList<Role>roles = new RoleServiceImpl().getRoleList();
        resp.setContentType("application/json");//设置返回JSON值
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(roles));
        writer.flush();
        writer.close();
    }

    //查询用户信息
    public void query(HttpServletRequest req, HttpServletResponse resp){
        //从前端获取参数
        String queryName = req.getParameter("queryname");
        String queryUserRoleString = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");

        int queryUserRole = 0;

        //获取用户列表
        UserService userService = new UserServiceImpl();

        //第一次请求，一定是访问第一页，页面大小固定
        int pageSize = Constants.PAGE_SIZE;
        int currentPageNo = 1;

        if(queryName != null){
            req.setAttribute("queryUserName",queryName);
        }
        if(!StringUtils.isNullOrEmpty(queryUserRoleString)){
            //角色传入的参数不为空则转换为整数类型
            queryUserRole = Integer.parseInt(queryUserRoleString);
            req.setAttribute("queryUserRole",queryUserRole);
        }
        if(!StringUtils.isNullOrEmpty(pageIndex)){
            currentPageNo = Integer.parseInt(pageIndex);
        }

        //获取用户总数
        int userCount = userService.getUserCount(queryName, queryUserRole);
        //分页支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setPageSize(pageSize);
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setTotalCount(userCount);

        int totalPageCount = pageSupport.getTotalPageCount();

        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > pageSize){
            currentPageNo = totalPageCount;
        }

        //获取用户列表
        ArrayList<User> userList = userService.getUserList(queryName, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList",userList);

        //获取角色列表
        ArrayList<Role> roleList = new RoleServiceImpl().getRoleList();
        req.setAttribute("roleList",roleList);

        req.setAttribute("totalCount",userCount);//总数
        req.setAttribute("currentPageNo",currentPageNo);//当前页
        req.setAttribute("totalPageCount",totalPageCount);//总页数

        //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //添加用户
    public void add(HttpServletRequest req, HttpServletResponse resp){
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.valueOf(gender));
        user.setPhone(phone);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreationDate(new Date());
        int cid = Math.toIntExact(((User) req.getSession().getAttribute(USER_SESSION)).getId());
        user.setCreatedBy(cid);

        UserService userService = new UserServiceImpl();
        if(userService.addUser(user)){
            try {
                resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                req.getRequestDispatcher("useradd.jsp").forward(req, resp);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        }
    }

    //验证旧密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        //从Session中拿密码
        Object o = req.getSession().getAttribute(USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        //万能的Map:结果集
        HashMap<String, String> resultMap = new HashMap<String, String>();

        if(o == null){//Session过期
            resultMap.put("result","sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){//输入的旧密码为空
            resultMap.put("result","error");
        }else {
            String userPassword = ((User) o).getUserPassword();
            if(oldpassword.equals(userPassword)){//密码正确
                resultMap.put("result","true");
            }else {
                resultMap.put("result","false");
            }
        }

        try {
            resp.setContentType("application/json");//设置返回JSON值
            PrintWriter writer = resp.getWriter();
            //JSONArray 阿里巴巴的JSON工具类，转换格式
            /*
            resultMap = ["result","sessionerror","result","error"]
            Json格式 = {key:value}
             */
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //从Session中拿ID
        Object o = req.getSession().getAttribute(USER_SESSION);
        String newpassword = req.getParameter("newpassword");
//        String oldpassword = req.getParameter("oldpassword");

        boolean flag = false;

        if(o == null){//Session中不存在用户信息 需要重新登录验证
            req.setAttribute("message","当前账号信息异常，请重新登录");
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
            return;
//        }else if(StringUtils.isNullOrEmpty(oldpassword) || !oldpassword.equals(((User)o).getUserPassword())){
//            //旧密码不正确
//            req.setAttribute("message","旧密码不正确");
        }else if(StringUtils.isNullOrEmpty(newpassword)){
            //新密码不规范
            req.setAttribute("message","新密码存在问题");
        }else {//修改密码
            UserService userService = new UserServiceImpl();
            flag = userService.updatePwd(((User) o).getId(), newpassword);
            if(flag){
                req.setAttribute("message","修改密码成功，请退出，使用新密码登录");
                //密码修改成功 移除当前Session
                req.getSession().removeAttribute(USER_SESSION);
            }else {
                req.setAttribute("message","密码修改失败");
            }
        }


        req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }


}
